package com.java.basis.thread.cas.atomic;

import javax.xml.transform.sax.SAXTransformerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 原子累加器的使用
 * 比较 AtomicLong 与 LongAdder
 * LongAdder的性能更好，是从1.8开始的
 *
 * @author wangning
 * @create 2022-01-29 10:38
 */
public class Test06 {
	public static void main(String[] args) {
		demo(
				() -> new AtomicLong(0),
				AtomicLong::getAndIncrement
		);//时间：41ms

		demo(LongAdder::new, LongAdder::increment);//时间：21ms

	}

	/**
	 *
	 * @param adderSupplier ()-结果，提供累加对象
	 * @param action 执行累加操作
	 * @param <T>
	 */
	private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
		T adder = adderSupplier.get();
		List<Thread> ts = new ArrayList<>();
		//四个线程，每个累加50万
		for (int i = 0; i < 4; i++) {
			ts.add(new Thread(() -> {
				for (int j = 0; j < 500000; j++) {
					action.accept(adder);
				}
			}));
		}
		long start = System.nanoTime();
		ts.forEach(Thread::start);
		ts.forEach(t -> {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		long end = System.nanoTime();
		System.out.println(adder + " cost" + (end - start) / 1000_000);
	}
}



